package org.batatasframework.support.database.sql.field;

import java.util.Iterator;
import java.util.List;

import org.batatasframework.support.database.DatabaseType;
import org.batatasframework.support.database.IdentifyTableBase;
import org.batatasframework.support.database.metadatas.FieldMetadata;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.database.sql.FieldFragment;
import org.batatasframework.support.database.sql.TableRuntimeMaster;
import org.batatasframework.support.database.sql.TableInstance;
import org.batatasframework.support.database.values.FieldValueHolder;
import org.batatasframework.support.database.values.StringValueHolder;


public class ConcatSelectFragment extends AbstractMultipleSelectFragment<FieldSourcable> implements FieldElement{
	private final String alias;
	
	public ConcatSelectFragment(TableRuntimeMaster master, String title){
		super(master, title);
		this.alias = master.getAliasGenerator().generate();
	}
	
	@Override
	public boolean enabled() {
		return true;
	}
	
	@Override
	public String getColumnName() {
		return master.getTableName() + '.' + alias;
	}
	
	@Override
	public TableInstance getTargetTable() {
		return master;
	}

	@Override
	public void toSqlString(StringBuilder sqlBuilder, IdentifyTableBase targetTable) {
		sqlBuilder.append("concat(");
		Iterator<FieldSourcable> itor = fields.iterator();
		while(itor.hasNext()){
			sqlBuilder.append(itor.next().getColumnName());
			if(itor.hasNext()){
				sqlBuilder.append(',');
			}
		}
		
		sqlBuilder.append(") as ").append(alias);
	}

	@Override
	public FieldMetadata find(String name) {
		if(alias.equals(name)) return this;
		return null;
	}
	
	@Override
	public void readSource(List<FieldMetadata> fields) {
		fields.add(this);
	}
	
	@Override
	protected FieldSourcable _buildField(TableInstance tableAlias, FieldMetadata fieldMetadata) {
		return new FieldFragment(tableAlias, fieldMetadata);
	}

	@Override
	public String getName() {
		return alias;
	}

	@Override
	public int getOrdinal() {
		return 0;
	}

	@Override
	public DatabaseType getDataType() {
		return DatabaseType.STRING;
	}

	@Override
	public TableMetadata getTableMetadata() {
		return master;
	}

	@Override
	public Object getFormat() {
		return null;
	}
	
	@Override
	public FieldValueHolder getValueHolder() {
		return new StringValueHolder(this, alias, null);
	}

//	@Override
//	public ValueHolder buildValueHolder() {
//		return new StringValueHolder(this, alias, null);
//	}

	@Override
	public String getAlias() {
		return alias;
	}
 
	@Override
	public FieldMetadata getSourceField() {
		return this;
	}
	@Override
	public String getcolumnName() {
		return alias;
	}
}
